var util = require('../../utils/util.js');
const api = require('../../config/api.js');
import WxValidate from '../../lib/wx-validate/WxValidate.js'
var that;
//获取应用实例
const app = getApp();
Page({
  /**
   * 页面的初始数据
   */
  data: {
    form: {
      principal: '',
      principalMobile: '',
      principalIdCardNo: '',
    },
    files: [],
    isFaceAuth: false, //人脸是否认证通过
    isAgree: true,
    jumpPage: '',
    needJump: false,
  },
  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    that = this;
    that.setData({
      isFaceAuth: app.globalData.isCert,
      'form.principalMobile': app.globalData.phoneNumber
    });
    if (options.page) {
      that.setData({
        jumpPage: decodeURIComponent(options.page),
        needJump: true,
      });
    }
    that.initValidate();
    //初始化认证经纪人信息
    that._initData();
  },
  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () { },
  _initData() {
    app.post(api.QueryTenant, { retry: 3, isAllow:true}).then(rsp => {
      if (rsp.data) {
        that.data.form.principal = rsp.data.principal;
        that.data.form.principalIdCardNo = rsp.data.principalIdCardNo;
        if (!util.isNullOrEmpty(rsp.data.faceUrl) && rsp.data.faceUrl.indexOf('/') != -1) {
          that.data.files.push(app.showImg(rsp.data.faceUrl));
        }
        if (rsp.data.isCert){
          //人脸是否认证成功
          app.globalData.isCert = true;
          wx.setStorageSync('isCert', true);
          var p = getCurrentPages();
          var preP = p[p.length - 2];
          preP.setData({ isUpdate: true });
        }
        that.setData({
          form: that.data.form,
          files:that.data.files,
          isFaceAuth: rsp.data.isCert?true:false,
        });
      }
    });
  },
  bindInput: function (e) {
    let name = e.currentTarget.dataset.name;
    let changeVal = {};
    changeVal[name] = e.detail.value;
    that.setData(changeVal);
  },
  previewFaceImage: function (e) {
    wx.previewImage({
      current: e.currentTarget.id, // 当前显示图片的http链接
      urls: that.data.files // 需要预览的图片http链接列表
    })
  },
  delFaceFile: function (e) { //删除人脸照
    let index = e.currentTarget.dataset.index;
    that.setData({
      files: util.arrayUtil.delByIndex(that.data.files, index),
    });
  },
  chooseImage: function (e) {
    if (that.data.files.length >= 1) {
      util.toast.fail('最多上传1张')
      return false;
    }
    wx.chooseImage({
      count: 1,
      sizeType: ['compressed'],
      sourceType: ['album', 'camera'],
      success: function (res) {
        that.setData({
          files: that.data.files.concat(res.tempFilePaths)
        });
      }
    })
  },
  submitForm: function (e) {
    const params = e.detail.value
    //console.log(params)
    // 传入表单数据，调用验证方法
    if (!this.WxValidate.checkForm(params)) {
      const error = this.WxValidate.errorList[0]
      util.toast.fail(error.msg);
      return false
    }
    //实名是否通过
    if (!that.data.isFaceAuth) {
      if (that.data.files.length <= 0) {
        util.confirm.modal('请上传人脸正面照!');
        return false;
      }
    }
    util.confirm.openExt('请确认信息无误？', function () {
      util.toast.loading('数据提交中...', 20);
      //人脸照片
      var faceFs = that.data.files[0];
      //上传人脸照片
      app.upload(faceFs, api.UploadImgOss).then(rlt => {
        var url = rlt.filePath;
        that.data.form.faceUrl = url;
        that.data.form.isAllow = true;
        that.data.form.isAgree = that.data.isAgree; //是否保险
        app.postPure(api.FaceAuth, that.data.form, { isAllow:true}).then(rsp => {
          //人脸是否认证成功
          app.globalData.isCert = true;
          wx.setStorageSync('isCert', true);
          if(that.data.needJump){
            wx.navigateTo({
              url: '/' + that.data.jumpPage,
            })
          }else{
            var p = getCurrentPages();
            var preP = p[p.length - 2];
            preP.setData({ isUpdate: true });
            wx.navigateBack({
              delta: 1
            })
          }
        }).catch((err) => {
          that.delFace();
          console.log('err', err);
        });
      });
    });
  },
  delFace() {
    //删除人脸正照
    if (that.data.form.faceUrl && that.data.form.faceUrl.indexOf('/') != -1) {
      app.removeFile(that.data.form.faceUrl, api.RemoveImgOss);
    }
  },
  onUnload() {
  },
  initValidate() {
    // 验证字段的规则
    const rules = {
      principal: {
        required: true,
      },
      principalIdCardNo: {
        required: true,
        idcard: true,
      }
    }

    // 验证字段的提示信息，若不传则调用默认的信息
    const messages = {
      principal: {
        required: '请输入姓名',
      },
      principalIdCardNo: {
        required: '请输入证件号码',
        idcard: '证件号码格式错误',
      }
    }
    // 创建实例对象
    this.WxValidate = new WxValidate(rules, messages)
  },
  onPullDownRefresh(){
    wx.stopPullDownRefresh();
  },
  lookAgreement() {
    wx.navigateTo({
      url: '/pages/insurance/instructions',
    })
  },
  agree() {
    that.setData({
      isAgree: !that.data.isAgree
    });
  },
})